import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../models/family_member.dart';
import '../providers/family_providers.dart';
import '../widgets/member_list_item.dart';
import '../widgets/add_member_dialog.dart';
import '../widgets/invite_member_dialog.dart';
import '../widgets/mood_selector_dialog.dart';

/// 家庭成员屏幕
class FamilyMembersScreen extends ConsumerStatefulWidget {
  /// 路由名称
  static const routeName = '/family-members';

  const FamilyMembersScreen({Key? key}) : super(key: key);

  @override
  ConsumerState<FamilyMembersScreen> createState() => _FamilyMembersScreenState();
}

class _FamilyMembersScreenState extends ConsumerState<FamilyMembersScreen> {
  @override
  Widget build(BuildContext context) {
    final family = ref.watch(familyProvider);
    
    // 如果没有家庭数据，显示创建家庭界面
    if (family == null) {
      return _buildCreateFamilyScreen();
    }
    
    return Scaffold(
      appBar: AppBar(
        title: Text(family.name),
        actions: [
          // 设置按钮
          IconButton(
            icon: const Icon(Icons.settings),
            onPressed: () => _showFamilySettingsDialog(context),
          ),
        ],
      ),
      body: Column(
        children: [
          // 当前用户心情状态卡片
          if (family.currentUser != null) _buildCurrentUserMoodCard(family.currentUser!),
          
          // 家庭成员列表
          Expanded(
            child: ListView.builder(
              padding: EdgeInsets.symmetric(vertical: 8.h, horizontal: 16.w),
              itemCount: family.members.length,
              itemBuilder: (context, index) {
                final member = family.members[index];
                return MemberListItem(
                  member: member,
                  onTap: () => _showMemberDetailsDialog(context, member),
                  onEdit: member.isCurrentUser || family.creatorId == family.currentUser?.id
                      ? () => _showEditMemberDialog(context, member)
                      : null,
                );
              },
            ),
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () => _showAddMemberOptions(context),
        child: const Icon(Icons.add),
      ),
    );
  }

  /// 构建创建家庭界面
  Widget _buildCreateFamilyScreen() {
    final nameController = TextEditingController();
    final userNameController = TextEditingController();
    
    return Scaffold(
      appBar: AppBar(
        title: const Text('创建家庭'),
      ),
      body: Padding(
        padding: EdgeInsets.all(16.w),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            const Text(
              '欢迎使用家庭空间！',
              style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
              textAlign: TextAlign.center,
            ),
            SizedBox(height: 16.h),
            const Text(
              '创建一个家庭空间，邀请家人加入，共享家庭生活。',
              textAlign: TextAlign.center,
            ),
            SizedBox(height: 32.h),
            TextField(
              controller: nameController,
              decoration: const InputDecoration(
                labelText: '家庭名称',
                hintText: '例如：张家、李家',
                border: OutlineInputBorder(),
              ),
            ),
            SizedBox(height: 16.h),
            TextField(
              controller: userNameController,
              decoration: const InputDecoration(
                labelText: '您的名字',
                hintText: '您在家庭中的称呼',
                border: OutlineInputBorder(),
              ),
            ),
            SizedBox(height: 16.h),
            DropdownButtonFormField<FamilyRole>(
              decoration: const InputDecoration(
                labelText: '您的角色',
                border: OutlineInputBorder(),
              ),
              value: FamilyRole.admin,
              items: FamilyRole.values.map((role) {
                return DropdownMenuItem<FamilyRole>(
                  value: role,
                  child: Text(role.displayName),
                );
              }).toList(),
              onChanged: (value) {},
            ),
            SizedBox(height: 32.h),
            ElevatedButton(
              onPressed: () {
                if (nameController.text.isNotEmpty && userNameController.text.isNotEmpty) {
                  ref.read(familyProvider.notifier).createFamily(
                        familyName: nameController.text,
                        creatorName: userNameController.text,
                      );
                }
              },
              style: ElevatedButton.styleFrom(
                padding: EdgeInsets.symmetric(vertical: 16.h),
              ),
              child: const Text('创建家庭'),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建当前用户心情状态卡片
  Widget _buildCurrentUserMoodCard(FamilyMember currentUser) {
    return Card(
      margin: EdgeInsets.all(16.w),
      child: Padding(
        padding: EdgeInsets.all(16.w),
        child: Column(
          children: [
            Row(
              children: [
                CircleAvatar(
                  radius: 30.r,
                  backgroundImage: currentUser.avatarUrl != null
                      ? NetworkImage(currentUser.avatarUrl!)
                      : null,
                  child: currentUser.avatarUrl == null
                      ? Icon(Icons.person, size: 30.r)
                      : null,
                ),
                SizedBox(width: 16.w),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        currentUser.name,
                        style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                      ),
                      Text(currentUser.role.displayName),
                      if (currentUser.birthday != null)
                        Text('生日：${currentUser.birthdayFormatted}'),
                    ],
                  ),
                ),
              ],
            ),
            SizedBox(height: 16.h),
            InkWell(
              onTap: () => _showMoodSelectorDialog(context),
              child: Container(
                padding: EdgeInsets.symmetric(vertical: 8.h, horizontal: 16.w),
                decoration: BoxDecoration(
                  color: currentUser.mood?.color.withOpacity(0.1) ?? Colors.grey.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(8.r),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    if (currentUser.mood != null) ...[  
                      Icon(
                        currentUser.mood!.icon,
                        color: currentUser.mood!.color,
                      ),
                      SizedBox(width: 8.w),
                      Text(
                        '当前心情：${currentUser.mood!.displayName}',
                        style: TextStyle(color: currentUser.mood!.color),
                      ),
                    ] else ...[  
                      const Icon(Icons.add_reaction),
                      SizedBox(width: 8.w),
                      const Text('设置我的心情'),
                    ],
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 显示添加成员选项
  void _showAddMemberOptions(BuildContext context) {
    showModalBottomSheet(
      context: context,
      builder: (context) {
        return SafeArea(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              ListTile(
                leading: const Icon(Icons.person_add),
                title: const Text('手动添加家庭成员'),
                onTap: () {
                  Navigator.pop(context);
                  _showAddMemberDialog(context);
                },
              ),
              ListTile(
                leading: const Icon(Icons.share),
                title: const Text('邀请家庭成员'),
                subtitle: const Text('生成邀请码分享给家人'),
                onTap: () {
                  Navigator.pop(context);
                  _showInviteMemberDialog(context);
                },
              ),
            ],
          ),
        );
      },
    );
  }

  /// 显示添加成员对话框
  void _showAddMemberDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => const AddMemberDialog(),
    );
  }

  /// 显示编辑成员对话框
  void _showEditMemberDialog(BuildContext context, FamilyMember member) {
    showDialog(
      context: context,
      builder: (context) => AddMemberDialog(memberToEdit: member),
    );
  }

  /// 显示邀请成员对话框
  void _showInviteMemberDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => const InviteMemberDialog(),
    );
  }

  /// 显示心情选择器对话框
  void _showMoodSelectorDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => const MoodSelectorDialog(),
    );
  }

  /// 显示成员详情对话框
  void _showMemberDetailsDialog(BuildContext context, FamilyMember member) {
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text(member.name),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              ListTile(
                leading: Icon(member.role.icon),
                title: Text('角色'),
                subtitle: Text(member.role.displayName),
              ),
              if (member.birthday != null)
                ListTile(
                  leading: const Icon(Icons.cake),
                  title: const Text('生日'),
                  subtitle: Text(member.birthdayFormatted),
                ),
              if (member.age != null)
                ListTile(
                  leading: const Icon(Icons.calendar_today),
                  title: const Text('年龄'),
                  subtitle: Text('${member.age}岁'),
                ),
              if (member.mood != null)
                ListTile(
                  leading: Icon(member.mood!.icon, color: member.mood!.color),
                  title: const Text('当前心情'),
                  subtitle: Text(
                    '${member.mood!.displayName}${member.moodUpdatedAtFormatted != null ? ' (${member.moodUpdatedAtFormatted})' : ''}',
                  ),
                ),
              if (member.phoneNumber != null)
                ListTile(
                  leading: const Icon(Icons.phone),
                  title: const Text('手机号'),
                  subtitle: Text(member.phoneNumber!),
                ),
              if (member.email != null)
                ListTile(
                  leading: const Icon(Icons.email),
                  title: const Text('邮箱'),
                  subtitle: Text(member.email!),
                ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('关闭'),
            ),
          ],
        );
      },
    );
  }

  /// 显示家庭设置对话框
  void _showFamilySettingsDialog(BuildContext context) {
    final family = ref.read(familyProvider);
    if (family == null) return;
    
    final nameController = TextEditingController(text: family.name);
    
    showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: const Text('家庭设置'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              TextField(
                controller: nameController,
                decoration: const InputDecoration(
                  labelText: '家庭名称',
                  border: OutlineInputBorder(),
                ),
              ),
              SizedBox(height: 16.h),
              ListTile(
                title: const Text('家庭创建时间'),
                subtitle: Text(
                  '${family.createdAt.year}年${family.createdAt.month}月${family.createdAt.day}日',
                ),
              ),
              ListTile(
                title: const Text('家庭创建者'),
                subtitle: Text(family.creator.name),
              ),
              ListTile(
                title: const Text('家庭成员数量'),
                subtitle: Text('${family.members.length}人'),
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context),
              child: const Text('取消'),
            ),
            TextButton(
              onPressed: () {
                if (nameController.text.isNotEmpty) {
                  ref.read(familyProvider.notifier).updateFamilyInfo(nameController.text);
                  Navigator.pop(context);
                }
              },
              child: const Text('保存'),
            ),
          ],
        );
      },
    );
  }
}
